/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.sys>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 /***************************************************************************
 * Name: message_builder.cpp
 *
 * Purpose: message builder and parser implementation
 *
 * Developer:
 *   wen.gu , 2021-05-10
 *
 * TODO:
 *
 ***************************************************************************/

 /******************************************************************************
 **    INCLUDES
 ******************************************************************************/

#include "message_builder.h"

#include <string.h>

/******************************************************************************
 **    MACROS
 ******************************************************************************/


/******************************************************************************
 **    VARIABLE DEFINITIONS
 ******************************************************************************/



/******************************************************************************
 **    FUNCTION DEFINITIONS
 ******************************************************************************/
MessageBuilder::MessageBuilder(MessagePtr msg)
    :msg_(msg)
{
    /** todo something */
}

MessageBuilder::~MessageBuilder()
{
    /** todo something */
}

int32_t MessageBuilder::build() 
{
    return (msg_ != nullptr) ? (msg_->message_size() + 4) : 0; /** the length of payload size */
}

bool MessageBuilder::toBuffer(uint8_t *buffer, int32_t size)
{
    if (msg_)
    {
    /**
     * the protocol of message data:
     * |session id(4 bytes)| message id(4 bytes)| message type(1 byte)|error_code(1 byte)| payload size(4 bytes)| payload data (variable length)| 
     */        
        uint8_t* pbuf = buffer;
        SessionId sid = msg_->session_id();
        MessageId mid = msg_->message_id();
        MessageType mt = msg_->type();
        ErrorCode errc = msg_->error_code();
        uint32_t  psize = msg_->payload_size();
        memcpy(pbuf, &sid, sizeof(sid));
        pbuf += sizeof(sid);

        memcpy(pbuf, &mid, sizeof(mid));
        pbuf += sizeof(mid);

        memcpy(pbuf, &mt, sizeof(mt));
        pbuf += sizeof(mt);

        memcpy(pbuf, &errc, sizeof(errc));
        pbuf += sizeof(errc); 

        if (psize > 0)
        {
            Message::PayloadPtr pp = msg_->payload();

            if (pp)
            {
                memcpy(pbuf, &psize, sizeof(psize));
                pbuf += sizeof(psize); 
                memcpy(pbuf, pp->data(), psize); 
            }
        }
             
        return true;
    }

    return false;
}



////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
MessageParser::MessageParser(MessagePtr msg)
    :msg_(msg)
{
    /** todo something */
}

MessageParser::~MessageParser()
{
    /** todo something */
}

bool MessageParser::parse(const uint8_t *buffer, int32_t size) 
{
    if (msg_ && (buffer != nullptr) && (size >= msg_->header_size()))
    {
    /**
     * the protocol of message data:
     * |session id(4 bytes)| message id(4 bytes)| message type(1 byte)|error_code(1 byte)| payload size(4 bytes)| payload data (variable length)| 
     */        
        const uint8_t* pbuf = buffer;
        SessionId sid;
        MessageId mid;
        MessageType mt;
        ErrorCode errc;
        uint32_t  psize;      

        memcpy(&sid, pbuf, sizeof(sid));
        pbuf += sizeof(sid);

        memcpy(&mid, pbuf, sizeof(mid));
        pbuf += sizeof(mid);

        memcpy(&mt, pbuf, sizeof(mt));
        pbuf += sizeof(mt);

        memcpy(&errc, pbuf, sizeof(errc));
        pbuf += sizeof(errc);

        memcpy(&psize, pbuf, sizeof(psize));
        pbuf += sizeof(psize);
        
        msg_->set_session_id(sid);
        msg_->set_message_id(mid);
        msg_->set_type(mt);
        msg_->set_error_code(errc);

        if (psize <= ((buffer + size) - pbuf)) /** todo is need process this as error */
        {
            Message::PayloadPtr payload = std::make_shared<Message::Payload>(psize);
            memcpy(payload->data(), pbuf, psize);
            msg_->set_payload(payload);
        }        

        return true;
    }

    return false;
}





